window.utility = {
    /**
             * @private
             * @param sUrl
             * @param oParameters
             * @returns {{url: (string|*), postData: Array}}
             * @private
             */
    _appendParameters: function (sUrl, oParameters) {
        // 把参数提出成为数组并排序
        var arrParameter = [];
        if (oParameters) {
            for (var i in oParameters) {
                var val = oParameters[i];
                if (typeof (val) != 'function') {
                    if (val === undefined || val === null || (typeof (val) == 'number' && isNaN(val))) {
                        val = '';
                    }
                    arrParameter.push({ key: i, originalValue: val, value: encodeURIComponent(val.toString()) });
                }
            }

            arrParameter.sort(function (a, b) {
                return a.value.length - b.value.length;
            });
        }

        sUrl = sUrl || '';
        var maxUrlLength = 2048; // 最大 URL 长度,取 IE6 的值（最小值）
        var postData = []; // 需要 POST 的数据
        var hash = '';
        var idxHash = sUrl.indexOf('#');
        if (idxHash > -1) {
            hash = sUrl.substr(idxHash);
            sUrl = sUrl.substr(0, idxHash);
        }

        var splitChar = '?';
        var queryIndex = sUrl.indexOf('?');
        var query = {};
        if (queryIndex > -1) {
            // 重新整理原来的参数,去除重复键
            var arrQueryString = sUrl.substr(queryIndex + 1).split('&');
            sUrl = sUrl.substr(0, queryIndex);
            for (var i = 0; i < arrQueryString.length; i++) {
                var exp = arrQueryString[i];
                var eqIndex = exp.indexOf('=');
                if (eqIndex > -1) {
                    var key = exp.substr(0, eqIndex);
                    var value = exp.substr(eqIndex + 1);
                    query[key] = value;
                }
            }

            // 更新原始的查询参数,去除重复键
            for (var i = 0; i < arrParameter.length; ++i) {
                var param = arrParameter[i];
                if (param.key in query) {
                    query[param.key] = param.value;
                    arrParameter.splice(i--, 1);
                }
            }

            // 拼接原始的 URL,并判断是否已超长
            for (var p in query) {
                var sNewParameter = splitChar + p + '=' + query[p];
                if (sUrl.length + sNewParameter.length + hash.length >= maxUrlLength) {
                    // 超过了最大长度,超过的数据使用 POST 发送
                    postData.push({ key: p, value: query[p] });
                }
                else {
                    sUrl += sNewParameter;
                    if (splitChar == '?') {
                        splitChar = '&';
                    }
                }
            }
        }

        // 合并查询参数到 URL
        for (var i = 0; i < arrParameter.length; ++i) {
            var param = arrParameter[i];
            var sNewParameter = splitChar + param.key + '=' + param.value;
            if (sUrl.length + sNewParameter.length + hash.length >= maxUrlLength) {
                // 超过了最大长度,超过的数据使用 POST 发送
                postData = postData.concat(arrParameter.slice(i, arrParameter.length));
                break;
            }
            else {
                sUrl += sNewParameter;
                if (splitChar == '?') {
                    splitChar = '&';
                }
            }
        }

        sUrl += hash;
        return { url: sUrl, postData: postData };
    },
    /**
    * 创建Url
    * @param  {String} sUrl        url字符串
    * @param  {Object} oParameters 附加参数
    * @return {String}             附件参数后的url字符串
    */
    buildUrl: function (sUrl, oParameters) {
        var result = this._appendParameters(sUrl, oParameters);
        if (result.postData.length) {
            throw new Error('参数过长');
        }

        return result.url;
    },
    /**
    * 获取所有url参数
    * @param {String} url 要解析的url地址，不指定默认为当前页面的url
    * @return {Object} 获取的参数对象
    * @example
    * //eg: http://www.xxx.com/index?key1=value1&key2=value2
    * var params = utility.getUrlParams();
    * var value1 = params['key1'];
    * var value2 = params['key2'];
    * var value2 = params['key2'];
    */
    getUrlParams: function () {
        var re = /(?:\\?|#|&)([^&#?=]*)=([^&#?=]*)(?:$|&|#)/ig;
        var url = window.location.href;
        var temp;
        var result = {};
        while ((temp = re.exec(url)) != null) {
            result[temp[1]] = temp[2];
        }
        return result;
    },
    getPrice: function (num) {
        num = parseFloat(num);
        if (_.isNumber(num)) {
            var cent = 2;
            num = num.toString().replace(/\$|\,/g, '');

            // 检查传入数值为数值类型  
            if (isNaN(num))
                num = "0";

            // 获取符号(正/负数)  
            sign = (num == (num = Math.abs(num)));

            num = Math.floor(num * Math.pow(10, cent) + 0.50000000001); // 把指定的小数位先转换成整数.多余的小数位四舍五入  
            cents = num % Math.pow(10, cent);       // 求出小数位数值  
            num = Math.floor(num / Math.pow(10, cent)).toString();  // 求出整数位数值  
            cents = cents.toString();        // 把小数位转换成字符串,以便求小数位长度  

            // 补足小数位到指定的位数  
            while (cents.length < cent)
                cents = "0" + cents;

            // 对整数部分进行千分位格式化.  
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++)
                num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));

            if (cent > 0)
                return (((sign) ? '' : '-') + num + '.' + cents);
            else
                return (((sign) ? '' : '-') + num);
        }
    },
    setCookie: function (name, value, time) {
        if (_.isNull(value)) {
            return false;
        }
        if (!_.isNull(value) && !_.isUndefined(value) && !_.isNaN(value)) {
            value = JSON.stringify(value);
        } else {
            return;
        }
        if (time) {
            $.cookie(name, value);
        } else {
            $.cookie(name, value, time);
        }
        return $.cookie(name);
    },
    getCookie: function (name) {
        if (!_.isUndefined($.cookie(name))) {
            return JSON.parse($.cookie(name));
        } else {
            return null;
        }
    }
}

var ns = function(star){

	var self = this;
	//计算最大数量
	var row;//总共行数
	var column;//总共列数
	
	//计算总数
	var maxNum;
	this.getMaxNum = function (){
		var winWidth = $(window).width();
		var winHeight = $(window).height() - 80;
		
		column = parseInt(winWidth/80);
		row = parseInt(winHeight/80);
		
		//配饰 + 星星 出现的最大数量
		maxNum = (row * column)*0.5;
		
		var minNum = parseInt(maxNum*0.2);//星星最小数量
		if(minNum <=1){
			minNum = 1;
		}
		
		star.starMaxNum = _.random(minNum, maxNum);//星星最大数量 = 总共数量的一半

		var level = utility.getUrlParams().level || 1;//难度系数，url需要带level参数
		
		var peishiMaxNum = parseInt(star.starMaxNum * 0.8);
		if(level == 1){//难度1
			peishiMaxNum = parseInt(star.starMaxNum * 0.8);//星星总数80%
		}else if(level == 2){//难度2
			peishiMaxNum = parseInt(star.starMaxNum * 0.7);//星星总数70%
		}else{//难度3
			peishiMaxNum = parseInt(star.starMaxNum * 0.6);//星星总数60%
		}
		star.peishiMaxNum = peishiMaxNum;//配饰数量
		
	}
	
	//计算所有出现的范围坐标
	this.position = [];
	this.getPosition = function(){
		var position = [];
		for(var i = 0;i < row; i++){//行
			for(var m = 0;m < column; m++){//列
				position.push({
					left: m *80,
					top: i *80
				})
			}
		}
		this.position = position;
	}
	
	this.setData = function(){
		
		self.getMaxNum();
		self.getPosition();
		
		var newPosition = [];
		var totalNum = star.starMaxNum + star.peishiMaxNum;
		newPosition = _.shuffle(self.position);
		newPosition = _.sample(newPosition,totalNum);
		_.each(newPosition,function(item, index){
			newPosition[index] = {
				left : _.random(item.left, (item.left + 30)),
				top : _.random(item.top, (item.top + 30))
			}
		});
		star.starPosition = _.first(newPosition, star.starMaxNum);
		star.peishiPosition = _.last(newPosition, star.peishiMaxNum);
	}
}

var star = new Vue({
	el: "#vue-star",
	data:{
		bgNum: 3,//背景图片数量
		starNum: 16,//星星图片数量
		peishiNum: 6,//配饰图片数量
		starMaxNum: 0,
		peishiMaxNum: 0,
		aniTime:["a-time06","a-time07"],
		aniDelay:["ani-delay03","ani-delay04","ani-delay05","ani-delay06","ani-delay07"],
		starPosition:[],
		peishiPosition:[]
		//showResult: false
	},
	watch:{
		
	},
	methods:{
		//获取背景
		getBg: function(){
			var num = Math.random() * this.bgNum;
			num = Math.ceil(num);
			return  "url(images/bg" + num + ".jpg)";
		},
		//获取星星
		getStar: function(){
			var num = Math.random() * this.starNum;//随机生成星星的图片编号
			num = Math.ceil(num);//取整
			return "images/star" + num + ".png";
		},
		//获取配饰
		getPeishi: function(){
			var num = Math.random()*this.peishiNum;//随机生成配饰的图片编号
			num = Math.ceil(num);//取整
			return "images/zs" + num + ".png";
		},
		//获取时间
		getAniTime:function(){
			var len = this.aniTime.length;
			var num = Math.random()*len;//随机生成配饰的图片编号
			num = parseInt(num);//取整
			return this.aniTime[num];
		},
		//获取延迟
		getDelayTime:function(){
			var len = this.aniDelay.length;
			var num = Math.random()*len;//随机生成配饰的图片编号
			num = Math.ceil(num);//取整
			return this.aniDelay[num];
		},
		//返回星星位置
		getStarPosition:function(index){
			return  {
				left:this.starPosition[index].left + "px",
				top:this.starPosition[index].top + "px"
			};
		},
		//返回配饰位置
		getPeishiPosition:function(index){
			return  {
				left:this.peishiPosition[index].left + "px",
				top:this.peishiPosition[index].top + "px"
			};
		},
		showRwsult:function(){
			$(".num-wrap").removeClass("hide");
			$(".js-shouwBtn").addClass("hide");
		},
		hideResult:function(){
			$(".num-wrap").addClass("hide");
			$(".js-shouwBtn").removeClass("hide");
		},
		angin:function(){
			this.hideResult();
			var angin = new ns(star);
			angin.setData();
		}
	},
	computed:{
		
	}
});


var newData = new ns(star);
newData.setData();

// Listen for orientation changes
//window.addEventListener("orientationchange", function() {
//	var changeData = new ns(star);
//	changeData.setData();
//}, false);

$(window).resize(function(e) {
    var changeData = new ns(star);
	changeData.setData();
});
